import { Component } from "react";
import { withRouter } from 'next/router';
import { targetUrl } from '@/utils';
import Cookies from 'js-cookie';
// css
import styles from '@/styles/CommonList.module.scss';
// 组件
import Breadcrumb from '@/components/Breadcrumb';
import ListItem from '@/pages_components/list/ListItem';
import HotProductPart from '@/pages_components/components/HotProductPart';
import Pagination from '@/pages_components/components/Pagination';
import Empty from '@/pages_components/list/Empty';
import Spin from '@/components/Spin';
// api
import { hotProductList_SSR } from '@/ssr';
import { searchProduct } from '@/api/search';

class Search extends Component {

    render() {
        const { loading, curr, total, list, hot_t } = this.state;
        return (
            <div className={styles['common-list-page']}>
                {/* loading */}
                <Spin loading={loading} />
                {/* 网页内容 */}
                <div className="max-content">
                    <div className={styles['cnt']}>
                        {/* 面包屑 */}
                        <Breadcrumb params={[{ name: '搜索', url: '/search' }]} />
                        {
                            !loading && <section className={styles['cnt-left']}>
                                <div className={styles['pro-list']}>
                                    {
                                        !list.length 
                                        ? <Empty />
                                        : list.map(item => <ListItem target={item.target} targetUrl={item.targetUrl} data={item} key={item.id} />)
                                    }
                                </div>
                                {/* 分页 */}
                                <Pagination onChange={this.onPageChange} curr={curr} total={total} size={10} />
                            </section>
                        }
                        <aside className={styles['cnt-right']}>
                            <HotProductPart product="热门景区" target="/ticket" list={hot_t} />
                        </aside>
                    </div>
                </div>
            </div>
        )
    }

    state = {
        loading: true,
        curr: 1,
        total: 0,
        list: [],
        hot_t: [], // 热门景区
    }

    async componentDidMount() {
        const { ssr: hot_t } = await hotProductList_SSR('/ticket');
        this.setState({
            hot_t: hot_t
        });
        this.doSearch({
            from: this.props.query.from
        });
    }

    // 搜索关键字不同，重新渲染
    shouldComponentUpdate(nextProps, nextState) {
        const { word: nextWord, from } = nextProps.query,
              { word: currWord } = this.props.query;
        if (nextWord !== currWord) {
            this.doSearch({
                currWord: nextWord,
                from
            })
        }
        return true
    }

    componentWillUnmount (){
        Cookies.remove('keywords');
    }

    // 过滤url
    filterUrl(item) {
        if (item.targetUrl.includes('/ticket')) {
            item.target = '/ticket'
        } else if (item.targetUrl.includes('/hotel')) {
            item.target = '/hotel'
        } else if (item.targetUrl.includes('/line')) {
            item.target = '/line'
        } else if (item.targetUrl.includes('/car')) {
            item.target = '/car'
        }
        return item
    }

    // 搜索
    doSearch({ currWord = "", from = "", current = 1 } = {}) {
        let keyword = Cookies.get('keywords') || "",
            { word } = this.props.query;
        if(currWord){
            keyword = currWord
        }else{
            if(word !== keyword){
                keyword = keyword
            }
            if(!keyword){
                keyword = word
            }
        }
        if(!keyword){
            this.setState({ loading: false });
            return false
        }
        this.setState({ loading: true });
        searchProduct({
            word: keyword,
            from,
            current
        }).then(res => {
            const { code, data } = res;
            if (code === 0 && data && data.records) {
                const { records, totalCount } = data;
                // 过滤掉非 “门票/酒店/线路/用车”
                const _list = records.map(item => {
                    item.targetUrl = targetUrl(item);
                    return this.filterUrl(item);
                });
                this.setState({
                    list: _list,
                    total: totalCount
                })
            }
            this.setState({
                loading: false
            })
        })
    }

    // 分页
    onPageChange = (curr) => {
        this.setState({
            loading: true,
            curr
        });
        this.doSearch({
            current: curr
        });
        window.scrollTo({
            top: 0
        });
    }
}

Search.getInitialProps = (ctx) => {
    const { pathname, query } = ctx;
    return { pathname, query }
}

export default withRouter(Search)
